class UsersController < ApplicationController

	layout "posts"

  before_filter :auth, :only => [:destroy, :edit, :update]

  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def show_users_posts
    @posts = Post.find_all_by_user_id(params[:id])
  end

  def index
    @users = User.find(:all)
  end

  def edit
    @user = User.find(params[:id])
    @user_levels = UserLevel.find(:all)
  end

  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user])
    redirect_to "../users/#{@user.id}"
  end

  def create
    @user = User.new(params[:user])
    if @user.save
			session[:user_id] = @user.id
			redirect_to home_path
		else
			render :template=>"users/new"
		end
  end

  def destroy
    @user = User.find(params[:id])  
    @user.destroy
    redirect_to "../users"
  end

	def toggle_admin
		if User.is_admin(session[:user_id]) && ( session[:user_id] != params[:id] )
			user = User.find_by_id(params[:id])
			user.toggle_admin_status
			user.save
			redirect_to "/users"
		end
	end

  private
  def auth
		return true if User.is_admin(session[:user_id]) || (session[:user_id].to_i == params[:id].to_i)
		redirect_to "../users"
  end

end
